/**
* 
*/
package com.naiterui.ehp.bs.doctor.utils;

import java.util.Arrays;
import java.util.Map;

import org.slf4j.Logger;

import com.naiterui.ehp.bp.support.exception.BusinessException;
import org.slf4j.LoggerFactory;

import com.naiterui.ehp.bs.doctor.exception.ExceptionCodes;
import com.naiterui.ehp.bp.utils.encypt.MD5;

/**
 * 签名校验
 * @author guoyongxiang
 * @since 2.9.0
 */
public class SignatureVerifyUtil {

    private static Logger LOGGER = LoggerFactory.getLogger(SignatureVerifyUtil.class);

    public static final String TIMESTAMP_PARAM = "t";
    /** 签名秘钥 */
    private static final String SECRET_KEY = "wu268m4iu8phczre4b";
    /** 签名链接有效期 */
    private static final Long EXPIRE = 60 * 1000L;

    public static boolean verifySign(Map<String, Object> params, String reqSign) throws BusinessException {
        // 校验有效期
        Long t = (Long) params.get(TIMESTAMP_PARAM);
        Long nowTime = System.currentTimeMillis();
        Long expiredAt = EXPIRE + t;
        if (nowTime + 1000 <= t || nowTime > expiredAt) {
            LOGGER.warn("请求已失效t:{}, expiredAt:{}", t, expiredAt);
            throw new BusinessException(ExceptionCodes.REQUSET_EXPIRE);
        }

        // 校验签名
        String[] paramArr = params.keySet().toArray(new String[] {});
        Arrays.sort(paramArr);

        StringBuilder bd = new StringBuilder();
        for (String param : paramArr) {
            bd.append(param).append("=").append(params.get(param)).append("&");
        }
        String str = bd.substring(0, bd.length() - 1);
        String sign = MD5.md5(str + SECRET_KEY);
        return sign.equals(reqSign);
    }

}
